package uid

import (
	"crypto/sha1"
	"io"
	"crypto/rand"
	"encoding/base64"
	"bytes"
)

const SaltSize = 16

func PasswordHash(plain string) (string, error) {
	buf := make([]byte, SaltSize, SaltSize + sha1.Size)
	_, err := io.ReadFull(rand.Reader, buf)
	if err != nil {
		return "", err
	}

	h := sha1.New()
	h.Write(buf)
	h.Write([]byte(plain))

	return base64.URLEncoding.EncodeToString(h.Sum(buf)), nil
}

func PasswordMatch(secret string, plain string) bool {
	data, _ := base64.URLEncoding.DecodeString(secret)
	if len(data) != SaltSize + sha1.Size {
		return false
	}

	h := sha1.New()
	h.Write(data[:SaltSize])
	h.Write([]byte(plain))

	return bytes.Equal(h.Sum(nil), data[SaltSize:])
}